package com.hzeport.bgs22emduty.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzeport.bgs22emduty.config.SystemConfig;
import com.hzeport.bgs22emduty.config.login.LoginCompoentService;
import com.hzeport.bgs22emduty.config.login.UserInfoDetailVO;
import com.hzeport.bgs22emduty.dto.ScreenAssessmentSaveDTO;
import com.hzeport.bgs22emduty.dto.ScreenDutyMessageDTO;
import com.hzeport.bgs22emduty.dto.work.ScreenDutyWorkDTO;
import com.hzeport.bgs22emduty.dto.work.ScreenDutyWorkDetailDTO;
import com.hzeport.bgs22emduty.dto.work.ScreenDutyWorkRemoveDTO;
import com.hzeport.bgs22emduty.dto.work.ScreenDutyWorkSaveDTO;
import com.hzeport.bgs22emduty.entity.*;
import com.hzeport.bgs22emduty.enums.DeleteFlagEnum;
import com.hzeport.bgs22emduty.outbound.AppendixRepository;
import com.hzeport.bgs22emduty.outbound.BaseDeptInfoRepository;
import com.hzeport.bgs22emduty.outbound.BasePersonInfoRepository;
import com.hzeport.bgs22emduty.outbound.ScreenDutyMessageRepository;
import com.hzeport.bgs22emduty.outbound.db.ScreenDutyMessageRepositoryImpl;
import com.hzeport.bgs22emduty.outbound.db.ScreenDutyWorkRepositoryImpl;
import com.hzeport.bgs22emduty.service.BaseDeptInfoService;
import com.hzeport.bgs22emduty.service.ParamDictionaryService;
import com.hzeport.bgs22emduty.service.ScreenDutyMessageService;
import com.hzeport.bgs22emduty.service.ScreenDutyWorkService;
import com.hzeport.bgs22emduty.util.WordUtils;
import com.hzeport.bgs22emduty.vo.file.FileVO;
import com.hzeport.bgs22emduty.vo.ls.ScreenDutyMessageSaveVO;
import com.hzeport.bgs22emduty.common.base.BaseEntity;
import com.hzeport.bgs22emduty.common.base.BaseResult;
import com.hzeport.bgs22emduty.common.base.BaseServiceImpl;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ${comments}
 *
 * @author code generator
 * @date 2023-02-14 09:39:44
 */
@Service
@Slf4j
public class ScreenDutyWorkServiceImpl extends BaseServiceImpl<ScreenDutyWorkRepositoryImpl, ScreenDutyWork> implements ScreenDutyWorkService {

    @Resource
    private LoginCompoentService loginCompoentService;
    @Resource
    private AppendixRepository appendixRepository;
    @Resource
    private BasePersonInfoRepository basePersonInfoRepository;

    @Override
    public Page<ScreenDutyWork> getScreenDutyWorkPage(ScreenDutyWorkDTO dto) {
//        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        LambdaQueryWrapper<ScreenDutyWork> queryWrapper = new LambdaQueryWrapper<>();
        if (!CollectionUtils.isEmpty(dto.getTimes())&&dto.getTimes().get(0)!=null){
            LocalDate localDate=LocalDate.parse(dto.getTimes().get(0));
            queryWrapper.ge(ScreenDutyWork::getCreateTime,localDate.atStartOfDay());
        }
        if (!CollectionUtils.isEmpty(dto.getTimes())&&dto.getTimes().get(1)!=null){
            LocalDate localDate=LocalDate.parse(dto.getTimes().get(1));
            queryWrapper.le(ScreenDutyWork::getCreateTime,localDate.atTime(23,59,59));
        }
        if (!StringUtils.isEmpty(dto.getKeyWord())){
            queryWrapper.like(ScreenDutyWork::getTitle,dto.getKeyWord());
        }
        queryWrapper.orderByDesc(ScreenDutyWork::getCreateTime);
        Page<ScreenDutyWork> page = repository.page(new Page<>(dto.getPageNum(), dto.getPageSize()), queryWrapper);
        page.getRecords().forEach(screenDutyWork->{
            if (screenDutyWork.getCreateBy()!=null) {
                BasePersonInfo personInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                    .eq(BasePersonInfo::getUserno, screenDutyWork.getCreateBy()),false);
                if (personInfo!=null){
                    screenDutyWork.setCreateBy(personInfo.getUsername());
                    screenDutyWork.setCreatePerson(personInfo.getUsername());
                }
            }
        });
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object saveWorks(ScreenDutyWorkSaveDTO dto) {
        UserInfoDetailVO userInfoDetailVO = loginCompoentService.getUserInfo();
        ScreenDutyWork screenDutyWork = new ScreenDutyWork();
        BeanUtil.copyProperties(dto,screenDutyWork);
        screenDutyWork.setCustomId(userInfoDetailVO.getCustomscode());
        screenDutyWork.setCustomName(userInfoDetailVO.getCustomsName());
        if (StringUtils.isEmpty(screenDutyWork.getId())) {
            screenDutyWork.setCreateBy(userInfoDetailVO.getUserId());
            screenDutyWork.setCreateTime(LocalDateTime.now());
            screenDutyWork.setUpdateBy(userInfoDetailVO.getUserId());
            screenDutyWork.setUpdateTime(LocalDateTime.now());
//            screenDutyWork.setCustomId(loginCompoentService.getCustomCodes());
//            screenDutyWork.setCustomName(loginCompoentService.getc());
            screenDutyWork.setDelFlag(DeleteFlagEnum.NOT_DELETE.getValue());
            repository.save(screenDutyWork);
        }else {
            ScreenDutyWork byId = repository.getById(screenDutyWork.getId());
            if (byId != null){
                screenDutyWork.setRecVersion(byId.getRecVersion());
            }
            screenDutyWork.setUpdateBy(userInfoDetailVO.getUserId());
            screenDutyWork.setUpdateTime(LocalDateTime.now());
            repository.updateById(screenDutyWork);
            List<String> list = appendixRepository.list(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId, screenDutyWork.getId())).stream().map(BaseEntity::getId).collect(Collectors.toList());
            list.removeAll(dto.getFiles().stream().map(FileVO::getId).collect(Collectors.toList()));
            appendixRepository.removeByIds(list);
//            appendixRepository.remove(new LambdaUpdateWrapper<Appendix>().eq(Appendix::getRelevanceId, screenDutyWork.getId()));
        }
        List<FileVO> files = dto.getFiles();
        if (!CollectionUtils.isEmpty(files)) {
            files.forEach(fileVO -> {
                LambdaUpdateWrapper<Appendix> wrapper = new LambdaUpdateWrapper<>();
                wrapper.eq(Appendix::getId, fileVO.getId()).set(Appendix::getRelevanceId, screenDutyWork.getId());
                appendixRepository.update(wrapper);
            });
        }
        return "1";
    }

    @Override
    public Object remove(ScreenDutyWorkRemoveDTO screenDutyWorkRemoveDTO) {
        return repository.removeById(screenDutyWorkRemoveDTO.getId());
    }

    @Override
    public ScreenDutyWorkDetailDTO detail(String id) {
        ScreenDutyWork screenDutyWork=repository.getById(id);
        if (screenDutyWork.getCreateBy()!=null) {
            BasePersonInfo personInfo = basePersonInfoRepository.getOne(new LambdaQueryWrapper<BasePersonInfo>()
                    .eq(BasePersonInfo::getUserno, screenDutyWork.getCreateBy()),false);
            if (personInfo!=null){
                screenDutyWork.setCreateBy(personInfo.getUsername());
                screenDutyWork.setCreatePerson(personInfo.getUsername());
            }
        }
        ScreenDutyWorkDetailDTO screenDutyWorkDetailDTO=new ScreenDutyWorkDetailDTO();
        BeanUtils.copyProperties(screenDutyWork,screenDutyWorkDetailDTO);
        List<FileVO> fileVOS = appendixRepository.list(new LambdaQueryWrapper<Appendix>().eq(Appendix::getRelevanceId, id))
                .stream().map(appendix -> {
                    FileVO fileVO = new FileVO();
                    BeanUtils.copyProperties(appendix,fileVO);
                    return fileVO;
                }).collect(Collectors.toList());
        screenDutyWorkDetailDTO.setFiles(fileVOS);
        return screenDutyWorkDetailDTO;
    }
}
